<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="手机号" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入手机号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option label="正常" value="1" />
          <el-option label="封禁" value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-back"
          size="mini"
          @click="handleBack"
        >返回首页</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-document-add"
          size="mini"
          @click="handleBatchAdd"
        >批量新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="registerList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" width="80" />
      <el-table-column label="手机号" align="center" prop="phone" width="150" />
      <el-table-column label="状态" align="center" prop="status" width="120">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status == 1" type="success">
            <i class="el-icon-check"></i> 正常
          </el-tag>
          <el-tag v-else-if="scope.row.status == 0" type="danger">
            <i class="el-icon-lock"></i> 封禁
          </el-tag>
          <span v-else>{{ scope.row.status }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.status == 1"
            size="mini"
            type="text"
            icon="el-icon-lock"
            @click="handleBan(scope.row)"
            style="color: #F56C6C;"
          >封禁</el-button>
          <el-button
            v-else-if="scope.row.status == 0"
            size="mini"
            type="text"
            icon="el-icon-unlock"
            @click="handleUnban(scope.row)"
            style="color: #67C23A;"
          >解封</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 单个新增对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号" maxlength="11" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">封禁</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 批量新增对话框 -->
    <el-dialog title="批量新增手机号" :visible.sync="batchOpen" width="600px" append-to-body>
      <el-form ref="batchForm" :model="batchForm" :rules="batchRules" label-width="100px">
        <el-form-item label="手机号列表" prop="phoneList">
          <el-input
            type="textarea"
            v-model="batchForm.phoneList"
            :rows="10"
            placeholder="请输入手机号，每行一个&#10;例如：&#10;13800138000&#10;13800138001&#10;13800138002"
          />
          <div style="margin-top: 10px; color: #909399; font-size: 12px;">
            <i class="el-icon-info"></i> 每行输入一个手机号，系统会自动去重和验证
          </div>
        </el-form-item>
        <el-form-item label="默认状态" prop="status">
          <el-radio-group v-model="batchForm.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">封禁</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitBatchForm">确 定</el-button>
        <el-button @click="cancelBatch">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listRegister, getRegister, delRegister, addRegister, updateRegister } from "@/api/system/register"

export default {
  name: "Register",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 注册手机号表格数据
      registerList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示批量新增弹出层
      batchOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        phone: null,
        status: null
      },
      // 表单参数
      form: {},
      // 批量表单参数
      batchForm: {},
      // 表单校验
      rules: {
        phone: [
          { required: true, message: "手机号不能为空", trigger: "blur" },
          { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号格式", trigger: "blur" }
        ],
        status: [
          { required: true, message: "状态不能为空", trigger: "change" }
        ]
      },
      // 批量表单校验
      batchRules: {
        phoneList: [
          { required: true, message: "手机号列表不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "状态不能为空", trigger: "change" }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询注册手机号列表 */
    getList() {
      this.loading = true
      listRegister(this.queryParams).then(response => {
        this.registerList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 取消批量新增
    cancelBatch() {
      this.batchOpen = false
      this.resetBatch()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        phone: null,
        status: 1
      }
      this.resetForm("form")
    },
    // 批量表单重置
    resetBatch() {
      this.batchForm = {
        phoneList: null,
        status: 1
      }
      this.resetForm("batchForm")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "新增手机号"
    },
    /** 批量新增按钮操作 */
    handleBatchAdd() {
      this.resetBatch()
      this.batchOpen = true
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          addRegister(this.form).then(response => {
            this.$modal.msgSuccess("新增成功")
            this.open = false
            this.getList()
          })
        }
      })
    },
    /** 批量提交按钮 */
    submitBatchForm() {
      this.$refs["batchForm"].validate(valid => {
        if (valid) {
          // 解析手机号列表，支持不同系统的换行符（\n 或 \r\n）
          const phoneList = this.batchForm.phoneList
            .replace(/\r\n/g, '\n')  // 统一换行符
            .replace(/\r/g, '\n')    // 处理旧Mac系统
            .split('\n')             // 按换行符分割
            .map(phone => phone.trim())  // 去除每行首尾空格
            .filter(phone => phone.length > 0)  // 过滤空行
          
          if (phoneList.length === 0) {
            this.$modal.msgError("请至少输入一个手机号")
            return
          }
          
          // 去重
          const uniquePhones = [...new Set(phoneList)]
          
          // 提示去重情况
          if (uniquePhones.length < phoneList.length) {
            const duplicateCount = phoneList.length - uniquePhones.length
            this.$modal.msgWarning(`已自动去除${duplicateCount}个重复的手机号`)
          }
          
          // 验证手机号格式
          const phoneRegex = /^1[3-9]\d{9}$/
          const invalidPhones = uniquePhones.filter(phone => !phoneRegex.test(phone))
          
          if (invalidPhones.length > 0) {
            this.$modal.msgError(`以下手机号格式不正确：\n${invalidPhones.join('\n')}`)
            return
          }
          
          // 批量添加
          const promises = uniquePhones.map(phone => {
            return addRegister({
              phone: phone,
              status: this.batchForm.status
            })
          })
          
          Promise.all(promises).then(() => {
            this.$modal.msgSuccess(`成功新增 ${uniquePhones.length} 个手机号`)
            this.batchOpen = false
            this.resetBatch()
            this.getList()
          }).catch(error => {
            this.$modal.msgError("批量新增失败，请检查是否有重复的手机号")
          })
        }
      })
    },
    /** 封禁操作 */
    handleBan(row) {
      this.$modal.confirm('是否确认封禁手机号"' + row.phone + '"？').then(() => {
        return getRegister(row.id).then(response => {
          const registerData = response.data
          registerData.status = 0
          return updateRegister(registerData)
        })
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("封禁成功")
      }).catch(() => {})
    },
    /** 解封操作 */
    handleUnban(row) {
      this.$modal.confirm('是否确认解封手机号"' + row.phone + '"？').then(() => {
        return getRegister(row.id).then(response => {
          const registerData = response.data
          registerData.status = 1
          return updateRegister(registerData)
        })
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("解封成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/register/export', {
        ...this.queryParams
      }, `register_${new Date().getTime()}.xlsx`)
    },
    /** 返回首页 */
    handleBack() {
      this.$router.push('/index')
    }
  }
}
</script>
